package com.github.fishlikewater.httppierce.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 用于检测channel的心跳handler 继承ChannelInboundHandlerAdapter，从而不需要实现channelRead0方法
 * </p>
 *
 * @author fishl
 */
@Slf4j
@RequiredArgsConstructor
public class DynamicServerHeartBeatHandler extends ChannelInboundHandlerAdapter {

    private final Channel channel;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent event) {
            if (event.state() == IdleState.READER_IDLE) {
                // 检查客户端连接是否存活
                if (this.determineNotActive(channel)) {
                    log.warn("client.not.active, will.to.close");
                    channel.close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    private boolean determineNotActive(Channel channel) {
        return !channel.isActive() || !channel.isOpen() || !channel.isWritable();
    }
}
